package alijk.dataView.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
/**
 * 获取数据库连接
 * @time 2014年10月30日 下午5:28:03
 * @author CheWenliang
 */
public class DBConnection {
	private static DBConnection conn = null;

	private static Connection jdbcConn = null;


	private DBConnection() {

	}

	public static DBConnection getInstance() {
		if (conn == null) {
			conn = new DBConnection();
		}

		return conn;
	}

	public Connection getConnection() {
		try {
			if (jdbcConn == null) {
				
					jdbcConn = getDataSource().getConnection();
				
				}else if(jdbcConn.isClosed()){
					jdbcConn = getDataSource().getConnection();
				}

		}catch (SQLException e) {
			e.printStackTrace();
		}

		return jdbcConn;
	}

	private DataSource getDataSource() {
		BasicDataSource dataSource = null;

		Properties p = new Properties();

		InputStream in = this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");
		try {
			//加载配置文件
			p.load(in);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			//得到dataSource
			dataSource = (BasicDataSource) BasicDataSourceFactory
					.createDataSource(p);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return dataSource;
	}

}
